#ifndef _CONFIG_READER_H_
#define _CONFIG_READER_H_
#include "ServerInfo.h"
#include <map>
#include <vector>
#include <string>
using namespace std;

#include "../tinyxml/tinyxml.h"
#include "../tinyxml/tinystr.h"
#include "configlib.h"


class CONFIGLIB_API ConfigReader
{
protected:
	ConfigReader(void);
	~ConfigReader();
public:
	virtual bool Unload();
	virtual bool Load(const std::string& config_file="brokers.xml",
		bool bForceLoad=false);
	virtual std::string GetDefault();
	std::string GetFileName() const;
protected:
	TiXmlDocument *document;
	TiXmlElement  *root;
};

inline std::vector<TiXmlElement*> GetSubElements( TiXmlElement* parent,const std::string& tag_name="")
{
	std::vector<TiXmlElement*> sub_elements;
	if (parent)
	{
		TiXmlElement* elem=parent->FirstChildElement(/*tag_name.c_str()*/);
		while (elem)
		{
			sub_elements.push_back(elem);
			elem=elem->NextSiblingElement(/*tag_name.c_str()*/);
		}
	}
	return sub_elements;
}


inline std::string GetAttribute( TiXmlElement* elem,const std::string& attr_name)
{
	if (elem)
	{
		const char* sz_attr_val=elem->Attribute(attr_name.c_str());
		if (NULL==sz_attr_val)
		{
			return "";
		}
		return std::string(sz_attr_val);
	}
	return std::string("");
}

inline void SetAttribute(TiXmlElement* elem, const std::string& attr_name,const std::string& value)
{
	if (elem)
	{
		elem->SetAttribute(attr_name.c_str(),value.c_str());
	}
}

inline void SetAttribute(TiXmlElement* elem, const std::string& attr_name, double value)
{
	if (elem)
	{
		elem->SetDoubleAttribute(attr_name.c_str(), value);
	}
}

inline void SetAttribute(TiXmlElement* elem, const std::string& attr_name, int value)
{
	if (elem)
	{
		elem->SetAttribute(attr_name.c_str(), value);
	}
}


inline void SetInnerText(TiXmlElement* elem, const std::string& value)
{
	if (elem)
	{
		auto ptrTextNode = elem->FirstChild();
		TiXmlText* ptrText = dynamic_cast<TiXmlText*>(ptrTextNode);
		if (ptrText)
		{
			ptrText->SetValue(value.c_str());
		}
		else
		{
			ptrText = new TiXmlText(value.c_str());
			elem->LinkEndChild(ptrText);
		}
	}
}

inline std::string GetInnerText( TiXmlElement* elem )
{
	if (elem)
	{
		const char* sz_attr_val=elem->GetText();
		if (NULL==sz_attr_val)
		{
			return "";
		}
		return sz_attr_val;
	}
	return "";
}

#endif


